package com.summer.shopping.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.summer.shopping.domain.common.req.ReqHolder;
import com.summer.shopping.domain.dto.UserDTO;
import com.summer.shopping.domain.properties.JwtProperties;
import com.summer.shopping.domain.table.Product;
import com.summer.shopping.domain.table.User;
import com.summer.shopping.domain.table.dto.UserLoginDTO;
import com.summer.shopping.domain.table.dto.UserRegistDTO;
import com.summer.shopping.domain.table.vo.UserLoginVo;
import com.summer.shopping.service.UserService;
import com.summer.shopping.utils.JwtUtil;
import com.summer.shopping.utils.Result;
import com.summer.shopping.utils.ResultCodeEnum;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    JwtProperties jwtProperties;
    @PostMapping("login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("员工登录：{}", userLoginDTO);

        User user = userService.login(userLoginDTO);
        if (user == null){
            return Result.error("用户名或密码错误");
        }
        //登录成功后，生成jwt令牌
        Map<String,Object> claims = new HashMap<>();
        claims.put("userId",user.getId());
        claims.put("permission",user.getPermission());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        UserLoginVo userLoginVo = UserLoginVo.builder()
                .id(user.getId())
                .nickname(user.getNickname())
                .username(user.getUsername())
                .token(token)
                .build();

        return Result.ok(userLoginVo);
    }

    @GetMapping("logout")
    public Result<String> logout() {
        return Result.ok("退出登录");
    }

    @PostMapping("regist")
    public Result<String> regist(@RequestBody UserRegistDTO userRegistDTO){
        log.info("用户注册：{}",userRegistDTO);
        try {
            userService.userRegist(userRegistDTO);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(ResultCodeEnum.USERNAME_USED.getMessage());
        }
        return Result.ok("注册成功");
    }


    // 更新用户信息
    @PutMapping
    public Result updateUser(@RequestBody UserDTO userDTO) {
        User user = new User();
        if (!"".equals(userDTO.getUsername())){
            user.setUsername(userDTO.getUsername());
        }
        if (!"".equals(userDTO.getNickname())){
            user.setNickname(userDTO.getNickname());
        }
        if (!"".equals(userDTO.getPhone())){
            user.setPhone(userDTO.getPhone());
        }
        if (!"".equals(userDTO.getEmail())){
            user.setEmail(userDTO.getEmail());
        }
        if (!"".equals(userDTO.getAvator())){
            user.setAvator(userDTO.getAvator());
        }
        Long userId = ReqHolder.getUserId();
        //设置头像
        user.setId(userId);
        userService.updateById(user);
        return Result.ok("success");
    }
    // 根据ID查询用户信息（更新表单时，需要先查一下）
    @GetMapping("/{id}")
    public Result<User> getUserInfoById(@PathVariable Long id) {
        User byId = userService.getById(id);
        return Result.ok(byId);
    }


}
